package com.crm.dao.saling;

import com.crm.pojo.Contract;
import com.crm.vo.ContractVO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dr5hx on 2018/8/3
 */
public interface ContractDao extends CrudRepository<Contract, Long> {
    /**
     * 得到未删除合同总数
     *
     * @return
     */
    @Query("select count(c) from Contract  c where c.contractIsDel='否'")
    public Long getContractExistCount();

    /**
     * 分页查询合同vo列表
     *
     * @param pageable
     * @return
     */
    @Query("select new com.crm.vo.ContractVO(contract,clientinfo.cname,userinfo.uname,saleplan.planName)" +
            " from Contract contract,ClientInfo clientinfo,Userinfo userinfo,SalePlan saleplan where clientinfo.cid=contract.fkCustomerId and contract.contractEmpno=userinfo.uId  and contract.contractIsDel='否' and saleplan.planId=contract.fkPlanId  order by contract.contractDoTime asc")
    public List<ContractVO> queryContractListAllByPage(Pageable pageable);

    /**
     * 使用合同id删除合同
     *
     * @param contractId
     */
    @Query(nativeQuery = true, value = "update CONTRACT set CONTRACT_IS_DEL='是' where CONTRACT_ID=?1")
    //更新数据库需要使用注解modifying
    @Modifying
    public void deleteContractById(Long contractId);

    /**
     * 获取所有的合同列表
     *
     * @return
     */

    @Query("select new com.crm.vo.ContractVO(contract,clientinfo.cname,userinfo.uname,saleplan.planName)" +
            " from Contract contract,ClientInfo clientinfo,Userinfo userinfo,SalePlan saleplan where clientinfo.cid=contract.fkCustomerId and contract.contractEmpno=userinfo.uId  and contract.contractIsDel='否' and saleplan.planId=contract.fkPlanId  order by contract.contractId asc")
    public List<ContractVO> showContractList();

    /**
     * 显示对应合同id的合同vo
     *
     * @param contractId
     * @return
     */
    @Query("select new com.crm.vo.ContractVO(contract,clientinfo.cname,userinfo.uname,saleplan.planName)" +
            " from Contract contract,ClientInfo clientinfo,Userinfo userinfo,SalePlan saleplan where clientinfo.cid=contract.fkCustomerId and contract.contractEmpno=userinfo.uId  and contract.contractIsDel='否' and saleplan.planId=contract.fkPlanId and contract.contractId=?1 order by contract.contractDoTime desc")
    public ContractVO getLoadContractVO(Long contractId);

    /**
     * 模糊查询订单合同（根据标题或id）
     *
     * @param q
     * @return
     */

    @Query(nativeQuery = true, value = "select * from CONTRACT where CONTRACT.CONTRACT_IS_DEL='否'and (CONTRACT.CONTRACT_ID like?1 or CONTRACT.CONTRACT_TOPIC like?1)")
    public ArrayList<Contract> getAllOrderBymh(String q);


}
